import 'dart:async';

import 'package:auto_orientation/auto_orientation.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:live_plugin/app_modules/app_modules.dart';
import 'package:live_plugin/features/me/bloc/me_bloc.dart';
import 'package:live_plugin/features/media_devices/bloc/media_devices_bloc.dart';
import 'package:live_plugin/features/peers/bloc/peers_bloc.dart';
import 'package:live_plugin/features/peers/ui/list_remote_streams.dart';
import 'package:live_plugin/features/producers/bloc/producers_bloc.dart';
import 'package:live_plugin/features/producers/ui/renderer/local_stream.dart';
import 'package:flutter/material.dart';
import 'package:live_plugin/features/room/bloc/room_bloc.dart';
import 'package:live_plugin/features/signaling/room_client_repository.dart';
import 'package:live_plugin/screens/room/controller/local_stream_controller.dart';
import 'package:live_plugin/screens/room/local_stream_view.dart';
import 'package:live_plugin/screens/room/remote_stream_view.dart';
import 'package:live_plugin/screens/room/room_modules.dart';
import 'package:live_plugin/screens/room/ui/leave_dialog.dart';
import 'package:live_plugin/screens/room/ui/members_list_dialog.dart';
import 'package:random_string/random_string.dart';

class Room extends StatefulWidget {
  static const String RoutePath = '/room';
  final String? url;
  final int? courseId;
  final String? classname;

  const Room({Key? key,this.url,this.courseId,this.classname}) : super(key: key);

  @override
  _RoomState createState() => _RoomState();
}

class _RoomState extends State<Room> {
  bool show = true;

  bool isOpenMicrophone = false;

  bool isVideoRecord = false;

  LocalStreamController _controller = LocalStreamController();

  bool isPortrait = true;

  StreamController<int> _controller2 = StreamController.broadcast();


  @override
  Widget build(BuildContext context) {
   return body();
  }

  Widget bodyBuilder(){
    return MultiBlocProvider(
      providers: getAppModules(),
      child: Builder(builder: (_){
        return MultiBlocProvider(
            providers: getRoomModules(url: widget.url ?? ""),
            child: RepositoryProvider(
              lazy: false,
              create: (innerContext) {
                final meState = innerContext.read<MeBloc>().state;
                String displayName = meState.displayName;
                String id = meState.id;
                final roomState = innerContext.read<RoomBloc>().state;
                String url = roomState.url;

                Uri? uri = Uri.parse(url);


                return RoomClientRepository(
                  peerId: id,
                  displayName: displayName,
                  // url: 'wss://192.168.6.138:4443',
                  url: 'http://8.141.171.155:80',
                  // url: url.isEmpty
                  //     ? 'wss://${uri.host}:4443'
                  //     : 'wss://v3demo.mediasoup.org:4443',
                  roomId: uri.queryParameters['roomId'] ??
                      uri.queryParameters['roomid'] ??
                      randomAlpha(8).toLowerCase(),
                  peersBloc: innerContext.read<PeersBloc>(),
                  producersBloc: innerContext.read<ProducersBloc>(),
                  meBloc: innerContext.read<MeBloc>(),
                  roomBloc: innerContext.read<RoomBloc>(),
                  mediaDevicesBloc: innerContext.read<MediaDevicesBloc>(),
                )..join();
              },
              child: body(),
            ));
      }),
    );
  }

  Widget body(){
    return Scaffold(
      appBar: appBar,
      body: GestureDetector(
        onTap: toggle,
        child: Stack(
          fit: StackFit.expand,
          children: [
            LocalStreamView(
              controller: _controller,
            ),
            Positioned(
              child: imageWgt,
              left: 0,
              top: 0,
            ),
            // ListRemoteStreams(),
            // LocalStream(),
            /*Positioned(
              child: SizedBox(
                width: 80,
                height: 120,
                child: RemoteStreamView(
                  controller: _controller2,
                ),
              ),
              right: 0,
              top: 0,
            ),*/
          ],
        ),
      ),
      bottomNavigationBar: bottomActionBar,
    );
  }

  AppBar? get appBar {
    if(!isPortrait && !show){
      return null;
    }
    return AppBar(
      elevation: 0,
      backgroundColor: Color(0xFF232426),
      titleSpacing: 0,
      centerTitle: true,
      title: Builder(
        builder: (context) {
          return Text(
            '${widget.classname}',
            style: TextStyle(
                color: Colors.white,
                fontSize: 13
            ),
          );
        },
      ),
      leading: Builder(
        builder: (innerCtx){
          return IconButton(
            icon: Icon(Icons.arrow_back_ios, color: Colors.white,size: 18,),
            onPressed: () {
              LeaveDialog.show(
                  context,
                  onSure: (){
                    Navigator.pop(context);
                  }
              );
            },
          );
        },
      ),
      actions: [
        GestureDetector(
          child: Container(
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(right: 9),
            child: Text(
              "结束",
              style: TextStyle(
                fontSize: 15,
                color: Color(0xFFFC2C1C)
              ),
            ),
          ),
          onTap: (){
            LeaveDialog.show(
              context,
              onSure: (){
                Navigator.pop(context);
              }
            );
          },
        )
      ],
    );
  }

  Widget get imageWgt {
    if(widget.url != null){
      return UnconstrainedBox(
        child: Container(
          color: Color(0xFFF7F7F7),
          child: Image.network(
              widget.url!,
              width: 80,
              height: 120,),
        ),
      );
    }
    return Container();
  }

  Widget? get bottomActionBar {
    if(!isPortrait && !show){
      return null;
    }

    return Container(
      width: double.infinity,
      height: 60,
      color: Color(0xFF232426),
      child: Row(
        children: [
          Expanded(
            child: InkWell(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset(
                    isOpenMicrophone ? "assets/images/ic_mic_open.png" : "assets/images/ic_mic_off.png",
                    width: 25,
                    height: 25,
                    color: Colors.white),
                SizedBox(height: 2.5),
                Text(
                  isOpenMicrophone ? "关闭" : "开启",
                  style: TextStyle(
                      fontSize: 11,
                      color: Color(0xFFD8D8D8)
                  ),
                )
              ],
            ),
            onTap: toggleMicrophone,
          ),
          ),
          Expanded(
              child:InkWell(
                child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset(
                    isVideoRecord ? "assets/images/ic_video_open.png" : "assets/images/ic_video_off.png",
                    width: 25,
                    height: 25,
                    color: Colors.white,
                  ),
                  SizedBox(height: 2.5),
                  Text(
                    isVideoRecord ? "停止" : "继续",
                    style: TextStyle(
                        fontSize: 11,
                        color: Color(0xFFD8D8D8)
                    ),
                  )
                ],
              ),
                onTap: toggleVideoRecord,
              ),
          ),
          Expanded(
            child:InkWell(
            onTap: toggleSwitch,
            child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset(
                  "assets/images/ic_video_check.png",
                  width: 25,
                  height: 25,
                  color: Colors.white),
              SizedBox(height: 2.5),
              Text(
                "切换",
                style: TextStyle(
                    fontSize: 11,
                    color: Color(0xFFD8D8D8)
                ),
              )
            ],
          ),),
          ),
          Expanded(
            child:InkWell(
            child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset(
                  "assets/images/ic_members.png",
                  width: 25,
                  height: 25,
                  color: Colors.white),
              SizedBox(height: 2.5),
              Text(
                "成员",
                style: TextStyle(
                    fontSize: 11,
                    color: Color(0xFFD8D8D8)
                ),
              )
            ],
          ),
            onTap: toggleMembers,
          ),
          ),
          Expanded(
            child: InkWell(
            onTap: toggleRotate,
            child:Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset(
                  "assets/images/ic_screen_rotate.png",
                  width: 25,
                  height: 25,
                  color: Colors.white),
              SizedBox(height: 2.5),
              Text(
                "旋转",
                style: TextStyle(
                    fontSize: 11,
                    color: Color(0xFFD8D8D8)
                ),
              )
            ],
          ),),
          ),
        ],
      ),
    );
  }

  void toggle() {
    setState(() {
      show = !show;
      if(show){
        Future.delayed(Duration(seconds: 1,milliseconds: 500),(){
          setState(() {
            show = false;
          });
        });
      }
    });
  }

  ///控制是否开启麦克风
  void toggleMicrophone(){
    setState(() {
      isOpenMicrophone = !isOpenMicrophone;
      if(isOpenMicrophone){
        _controller.add(LocalSEvent.OpenMicrophone);
      }else {
        _controller.add(LocalSEvent.OffMicrophone);
      }
    });
  }

  ///控制录制状态
  void toggleVideoRecord(){
    setState(() {
      isVideoRecord = !isVideoRecord;
      if(isVideoRecord){
        _controller.add(LocalSEvent.StartRecord);
      }else{
        _controller.add(LocalSEvent.StartRecord);
      }
    });
  }

  ///切换
  void toggleSwitch(){
    _controller.add(LocalSEvent.SwitchCar);
  }

  ///成员
  void toggleMembers(){
    MembersListDialog.show(context);
  }

  ///旋转
  void toggleRotate(){
    if(isPortrait){
      AutoOrientation.landscapeAutoMode();
      isPortrait = !isPortrait;
      setState(() {
        show = false;
      });
    }else{
      AutoOrientation.portraitAutoMode();
      isPortrait = !isPortrait;
    }
  }
}
